<template>
  <el-dialog
    v-model="dialogVisible"
    width="580"
    :title="action === 'edit' ? '编辑巨量绑定数据' : action === 'add' ? '添加巨量绑定数据' : '巨量绑定数据详情'"
    draggable
    appendToBody
    destroyOnClose
    lockScroll
    :closeOnClickModal="false"
    :beforeClose="dialogClose"
  >
    <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
    <template v-else-if="pageLoad.loadState === false">
      <el-form ref="elFormRef" v-auto-animate v-AutoAnimate :model="formData" :rules="rules" scrollToError :disabled="disabled">
        <el-form-item label="广告主账号" labelWidth="10em" prop="thirdAdvertiserId">
          <el-select
            v-model="formData.thirdAdvertiserId"
            filterable
            remote
            reserveKeyword
            placeholder="广告主账号"
            :no-data-text="thirdAdvertiserNoDataText"
            :remoteMethod="thirdAdvertiserIdRemoteMethod"
            :loading="thirdAdvertiserSelectorLoading"
          >
            <el-option
              v-for="item in thirdAdvertiserIdOptions"
              :key="item.thirdAdvertiserId"
              :label="item.thirdAdvertiserName"
              :value="item.thirdAdvertiserId"
              @click="thirdAdvertiserItemClick(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推广链接ID" labelWidth="10em" prop="referralLinkId">
          <el-input v-model="formData.referralLinkId" :maxlength="255" clearable placeholder="请输入推广链接ID"></el-input>
        </el-form-item>
        <!--        <el-form-item label="推广链接名称" labelWidth="10em" prop="referralLinkName"> -->
        <!--          <el-input v-model="formData.referralLinkName" :maxlength="255" clearable placeholder="请输入推广链接名称"></el-input> -->
        <!--        </el-form-item> -->
        <el-form-item label="短剧名称" labelWidth="10em" prop="dramaTitle">
          <el-input v-model="formData.dramaTitle" :maxlength="255" clearable placeholder="请输入短剧名称"></el-input>
        </el-form-item>
        <el-form-item label="投手名称" labelWidth="10em" prop="createName">
          <el-input v-model="formData.createName" :maxlength="255" clearable placeholder="请输入投手名称"></el-input>
        </el-form-item>
        <el-form-item label="应用类型" labelWidth="10em" prop="appType">
          <box-from-border>
            <el-radio-group v-model="formData.appType">
              <el-radio label="抖小" :value="1"></el-radio>
              <el-radio label="微小" :value="3"></el-radio>
            </el-radio-group>
          </box-from-border>
        </el-form-item>
        <el-form-item label="推广链接类型" labelWidth="10em" prop="referralLinkType">
          <box-from-border>
            <el-radio-group v-model="formData.referralLinkType">
              <el-radio v-for="i in referralLinkTypeOptions" :key="i.value" :label="i.label" :value="i.value"></el-radio>
            </el-radio-group>
          </box-from-border>
        </el-form-item>
        <el-form-item v-if="action !== 'edit'" key="form-item-key1" label="状态" labelWidth="10em" prop="pullStatus">
          <box-from-border>
            <el-radio-group v-model="formData.pullStatus">
              <el-radio label="停用" :value="0"></el-radio>
              <el-radio label="启用" :value="1"></el-radio>
            </el-radio-group>
          </box-from-border>
        </el-form-item>
        <el-form-item v-if="action !== 'add'" key="el-form-item-2" label="拉取数据开始时间" labelWidth="10em" prop="createTime">
          <el-input v-model="formData.createTime" :maxlength="255" disabled placeholder="-"></el-input>
        </el-form-item>
        <el-form-item label="拉取数据结束时间" labelWidth="10em" prop="endTime">
          <base-date-picker
            v-model="formData.endTime"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            placeholder="请选择拉取数据结束时间"
            type="date"
            style="width: 100%"
            clearable
          ></base-date-picker>
        </el-form-item>
        <el-form-item v-if="!disabled" key="el-form-item-4" labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <base-empty
      v-else
      style="height: 100%"
      :description="pageLoad.description || ''"
      :imageSize="240"
      :loadState="pageLoad.loadState"
      :pageLoadButton="[{ text: '重新加载', callBack: getBaseDataAxios }]"
    ></base-empty>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus';
  import type { Response } from '@/utils/axios/axios';
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import {
    type OceAdvertiserReferralRelationItem,
    type ThirdAdvertiserIdOptions,
    addOceAdvertiserReferralRelation,
    queryAdvertiserInfo,
    updateOceAdvertiserReferralRelation,
  } from '@/api/marketing-management';
  import { referralLinkTypeOptions } from '@/views/app-main/marketing-management/selectorOptions.ts';

  type $EditShowData = {
    /** 操作 */
    action: 'edit';
    recordData: OceAdvertiserReferralRelationItem;
    /** 审核后的回调 */
    editCallBack?: () => void;
  };

  type $AddShowData = {
    /** 操作 */
    action: 'add';
    /** 审核后的回调 */
    addCallBack?: () => void;
  };

  type $DetailsShowData = {
    /** 操作 */
    action: 'details';
    recordData: OceAdvertiserReferralRelationItem;
  };
  type $ShowData = $AddShowData | $DetailsShowData | $EditShowData;

  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });

  let addCallBack: $AddShowData['addCallBack'] = undefined;
  let editCallBack: $EditShowData['editCallBack'] = undefined;

  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const action = ref<'add' | 'details' | 'edit'>();
  const loading = ref(false);

  const thirdAdvertiserSelectorLoading = ref(false);
  const thirdAdvertiserNoDataText = ref<string>('无数据');
  const thirdAdvertiserIdOptions = ref<ThirdAdvertiserIdOptions[]>([]);

  const disabled = computed(() => action.value === 'details');

  type FormData = OceAdvertiserReferralRelationItem & {
    appType: number;
    pullStatus: number;
    /** 广告主账号 */
    thirdAdvertiserId: string;
    /** 广告主账户名 */
    thirdAdvertiserName: string;
    thirdAdvertiserAppCode?: string;
  };

  const originReferralLinkId = ref<string | null>(null);
  const formData = reactive<FormData>({
    advertiserReferralId: null,
    referralLinkId: '',
    referralLinkName: '',
    thirdAdvertiserId: '',
    thirdAdvertiserName: '',
    dramaTitle: '',
    createName: '',
    endTime: '',
    createTime: '',
    pullStatus: 0,
    appType: 1,
    referralLinkType: 1,
    thirdAdvertiserAppCode: '',
    appCode: undefined,
  });

  /** 获取广告主信息 */
  const thirdAdvertiserIdRemoteMethod = async (query: string) => {
    if (query) {
      thirdAdvertiserSelectorLoading.value = true;

      const res = (await queryAdvertiserInfo({ thirdAdvertiserId: query }).catch((e) => {
        return e;
      })) as Response<ThirdAdvertiserIdOptions>;

      thirdAdvertiserSelectorLoading.value = false;

      if (res.code === 200) {
        if (res.data.thirdAdvertiserId && res.data.thirdAdvertiserName) {
          thirdAdvertiserIdOptions.value = [
            {
              thirdAdvertiserId: res.data.thirdAdvertiserId,
              thirdAdvertiserName: res.data.thirdAdvertiserName,
              thirdAdvertiserAppCode: res.data.appCode,
            },
          ];
        } else {
          thirdAdvertiserNoDataText.value = '无数据';
          thirdAdvertiserIdOptions.value = [];
        }
      } else {
        thirdAdvertiserIdOptions.value = [];
        if (res.msg) {
          thirdAdvertiserNoDataText.value = res.msg;
        }
      }
    } else {
      thirdAdvertiserIdOptions.value = [];
    }
  };

  /** 填充广告主名字 */
  const thirdAdvertiserItemClick = (val: ThirdAdvertiserIdOptions) => {
    formData.thirdAdvertiserName = val.thirdAdvertiserName;
    formData.thirdAdvertiserAppCode = val.thirdAdvertiserAppCode;
  };

  const rules = computed(() => {
    const _rules: FormRules<FormData> = {
      thirdAdvertiserId: [{ required: true, type: 'string', message: '请选择广告主账号', trigger: ['blur', 'change'] }],
      referralLinkName: [{ required: false, type: 'string', message: '请输入推广链接名称', trigger: ['blur', 'change'] }],
      referralLinkId: [{ required: true, type: 'string', message: '请输入推广链接id', trigger: ['blur', 'change'] }],
      dramaTitle: [{ required: true, type: 'string', message: '请输入短剧名称', trigger: ['blur', 'change'] }],
      createName: [{ required: true, type: 'string', message: '请输入投手名称', trigger: ['blur', 'change'] }],
      endTime: [{ required: false, type: 'string', message: '请选择拉取数据结束时间', trigger: ['blur', 'change'] }],
    };
    return _rules;
  });

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        if (action.value === 'edit') {
          await updateOceAdvertiserReferralRelation({ ...formData, endTime: formData.endTime ? `${formData.endTime.split(' ')[0]} 23:59:59` : '' });
          typeof editCallBack === 'function' && editCallBack();
          ElToast.success('修改成功');
        } else {
          await addOceAdvertiserReferralRelation({
            ...formData,
            advertiserReferralId: null,
            endTime: formData.endTime ? `${formData.endTime.split(' ')[0]} 23:59:59` : '',
          });
          typeof addCallBack === 'function' && addCallBack();
          ElToast.success('添加成功');
        }
        loading.value = false;
        hide();
      } catch (error) {
        loading.value = false;
        ElToast.error(error.msg || '提交失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  function show(data: $ShowData) {
    action.value = data.action;

    if (data.action === 'edit' || data.action === 'details') {
      originReferralLinkId.value = data.recordData.referralLinkId!;
      formData.advertiserReferralId = data.recordData.advertiserReferralId || null;
      formData.thirdAdvertiserId = data.recordData.thirdAdvertiserId || '';
      formData.thirdAdvertiserName = data.recordData.thirdAdvertiserName || '';
      formData.referralLinkId = String(data.recordData.referralLinkId) || '';
      formData.referralLinkName = data.recordData.referralLinkName || '';
      formData.pullStatus = data.recordData.pullStatus || 0;
      formData.appType = data.recordData.appType || 1;
      formData.referralLinkType = data.recordData.referralLinkType || 1;
      formData.dramaTitle = data.recordData.dramaTitle;
      formData.createName = data.recordData.createName;
      formData.endTime = data.recordData.endTime;
      formData.createTime = data.recordData.createTime;
      formData.thirdAdvertiserAppCode = data.recordData.appCode;

      if (data.recordData.thirdAdvertiserId && data.recordData.thirdAdvertiserName) {
        thirdAdvertiserIdOptions.value = [
          {
            thirdAdvertiserId: data.recordData.thirdAdvertiserId,
            thirdAdvertiserName: data.recordData.thirdAdvertiserName,
            thirdAdvertiserAppCode: data.recordData.appCode,
          },
        ];
      }
    } else {
      formData.advertiserReferralId = null;
      formData.thirdAdvertiserId = '';
      formData.thirdAdvertiserName = '';
      formData.referralLinkId = '';
      formData.referralLinkName = '';
      formData.pullStatus = 0;
      formData.appType = 1;
      formData.referralLinkType = 1;
      formData.dramaTitle = '';
      formData.createName = '';
      formData.endTime = '';
      formData.createTime = '';
      formData.thirdAdvertiserAppCode = '';
    }

    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;

    dialogVisible.value = true;

    getBaseDataAxios();
    pageLoad.loadState = false;
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /**
   * 隐藏
   */
  function dialogClose() {
    originReferralLinkId.value = null;
    dialogVisible.value = false;
  }

  /**
   * 是否修改referralLinkId
   */
  // function validOriginReferralLinkId() {
  //   if (originReferralLinkId.value) {
  //     if (formData.referralLinkId !== originReferralLinkId.value) {
  //       action.value = 'add';
  //     } else {
  //       action.value = 'edit';
  //     }
  //   }
  // }

  /** 请求 */
  async function getBaseDataAxios() {
    // try {
    //   pageLoad.loadState = true;
    //   pageLoad.loadState = false;
    // } catch (error) {
    //   pageLoad.loadState = 'err';
    //   pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    // }
  }

  defineExpose({ show, hide });
</script>
